package apiRedis;

import com.techindata.cacheredis.RedisConnectionPool;
import com.techindata.cacheredis.SerializeUtil;
import org.apache.log4j.Logger;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.Set;

/**
 * @author jixiang
 *         <p>
 *         <p>
 *         从缓存中得到单一值数据
 */
public class DynamicCacheGet {
    static Logger logger = Logger.getLogger(DynamicCacheGet.class);

    /**
     * @param key 存入到cache中
     * @return String 返回从缓存中得到的值，没有返回""
     **/
    public static String getValue(String servIp,String servPort,String passwd ,String key) {
        JedisPool pool = DynamicRedisPoolUtil.getJedisPool(servIp,servPort,passwd);
        String result = "";
        Jedis jedis = null;
        try {
            jedis = pool.getResource();

            //Set<String> keys=jedis.keys(key);
            try {
                //for(String k:keys){
                result = jedis.get(key);
                //}
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            }
        } catch (Exception e) {
            // 释放redis对象
            //pool.returnBrokenResource(jedis);
            logger.error(e.getMessage(), e);
        } finally {
            // 返还到连接池
            RedisConnectionPool.returnResource(pool, jedis);
        }
        return result;
    }

    public static Object getObject(String servIp,String servPort,String passwd ,String key) {
       JedisPool pool = DynamicRedisPoolUtil.getJedisPool(servIp,servPort,passwd);
        Object result = null;
        Jedis jedis = null;
        try {
            jedis = pool.getResource();
            result = SerializeUtil.unSerialize(jedis.get(key.getBytes()));
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        } finally {
           // jedis.close();
            RedisConnectionPool.returnResource(pool, jedis);
        }
        return result;
    }

    public static Set<String> getKeys(String servIp,String servPort,String passwd ,String keys) {
        JedisPool pool = DynamicRedisPoolUtil.getJedisPool(servIp,servPort,passwd);
        Set<String> result = null;
        Jedis jedis = null;
        try {
            jedis = pool.getResource();
            result = jedis.keys(keys);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        } finally {
            RedisConnectionPool.returnResource(pool, jedis);
        }
        return result;
    }


}
